package dk.ucn.datamatiker.saveme;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.URL;
import java.net.URLConnection;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.os.AsyncTask;
import android.util.Log;

public class TaxiRequest extends AsyncTask<String, Void, String> {
	private static final String BASE_URL = "http://balder.ucn.dk/dm77_gr2/SaveMe.svc/";
	private BufferedReader bufferedReader;
	private URL url;

	protected String doInBackground(String... paramStrings) {
		String fullURL = BASE_URL + paramStrings[0];
		String result = null;
		String inputLine;
		StringBuilder response = new StringBuilder();

		try {
			url = new URL(fullURL);
			URLConnection connection = url.openConnection();
			bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

			while ((inputLine = bufferedReader.readLine()) != null) {
				response.append(inputLine);
			}
			result = parseByDOM(response.toString());

		} catch (IOException ioException) {
			Log.e("TaxiRequest", "doInBackground", ioException);
		} finally {
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException ioException) {
					Log.e("TaxiRequest", "doInBackground", ioException);
				}
			}
		}
		return result;
	}

	protected void onPostExecute(String result) {
		super.onPostExecute(result);
	}

	private String parseByDOM(String response) {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db;
		Document doc;
		String result = null;
		try {
			db = dbf.newDocumentBuilder();
			doc = db.parse(new InputSource(new StringReader(response)));
			result = doc.getElementsByTagName("int").item(0).getTextContent();
		} catch (ParserConfigurationException parserConfigurationException) {
			Log.e("TaxiRequest", "parseByDOM", parserConfigurationException);
		} catch (SAXException saxException) {
			Log.e("TaxiRequest", "parseByDOM", saxException);
		} catch (IOException ioException) {
			Log.e("TaxiRequest", "parseByDOM", ioException);
		}
		return result;
	}
}